<?php
/**
 * amazon_il.php
 *
 * @package Amazon Inventory Loader
 * @copyright Copyright 2007-2008 Numinix Technology http://www.numinix.com
 * @copyright Copyright 2003-2006 Zen Cart Development Team
 * @copyright Portions Copyright 2003 osCommerce
 * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
 * @version $Id: amazon_il.php, v1.01b 04.29.2008 13:31:59 numinix $
 *
 */
	@define('AMAZON_IL_VERSION', '1.01b 04.29.2008 13:31:59');

	require('includes/application_top.php');

	@define('AMAZON_IL_OUTPUT_BUFFER_MAXSIZE', 1024*1024);
	@define('AMAZON_IL_CHECK_IMAGE', 'false');
	@define('AMAZON_IL_STAT', false);
	$anti_timeout_counter = 0; //for timeout issues as well as counting number of products processed
	$max_limit = false;
	$today = date("Y-m-d");
	@define('NL', "<br />\n");

	require(zen_get_file_directory(DIR_WS_LANGUAGES . $_SESSION['language'] .'/', 'amazon_il.php', 'false'));
	$languages = $db->execute("select code, languages_id from " . TABLE_LANGUAGES . " where name='" . 'English' . "' limit 1");


	echo TEXT_AMAZON_IL_STARTED . NL;
	echo TEXT_AMAZON_IL_FILE_LOCATION . DIR_FS_CATALOG . AMAZON_IL_DIRECTORY . AMAZON_IL_OUTPUT_FILENAME . NL;
	echo "Processing: Feed - " . (isset($_GET['feed']) && $_GET['feed'] == "yes" ? "Yes" : "No") . ", Upload - " . (isset($_GET['upload']) && $_GET['upload'] == "yes" ? "Yes" : "No") . NL;

if (isset($_GET['feed']) && $_GET['feed'] == "yes") {
	$fc->unlock(DIR_FS_CATALOG . AMAZON_IL_DIRECTORY);
	if (is_dir(DIR_FS_CATALOG . AMAZON_IL_DIRECTORY)) {
		if (!is_writeable(DIR_FS_CATALOG . AMAZON_IL_DIRECTORY)) {
			echo ERROR_AMAZON_IL_DIRECTORY_NOT_WRITEABLE . NL;
			die;
		}
	} else {
		echo ERROR_AMAZON_IL_DIRECTORY_DOES_NOT_EXIST . NL;
		die;
	}

	$stimer_feed = microtime_float();
	if (!get_cfg_var('safe_mode') && function_exists('safe_mode')) {
		set_time_limit(0);
	}

	$output_buffer = "";
	$outfile = DIR_FS_CATALOG . AMAZON_IL_DIRECTORY . AMAZON_IL_OUTPUT_FILENAME;
	if (file_exists($outfile)) {
// 		chmod($outfile, 0777);
	    $fc->unlock($outfile);
	} else {
		fopen($outfile, "w");
	}
	if (is_writeable($outfile)) {
		$categories_array = zen_amazon_category_tree();
		if (AMAZON_IL_ATTRIBUTES == 'false') {
			$products_query = "SELECT distinct(p.products_id), p.products_model, p.products_weight, pd.products_name, pd.products_description, p.products_image, p.products_tax_class_id, p.products_price_sorter, GREATEST(p.products_date_added, IFNULL(p.products_last_modified, 0), IFNULL(p.products_date_available, 0)) AS base_date, m.manufacturers_name, p.products_quantity, pt.type_handler, s.specials_new_products_price, s.expires_date
											 FROM " . TABLE_PRODUCTS . " p
												 LEFT JOIN " . TABLE_MANUFACTURERS . " m ON (p.manufacturers_id = m.manufacturers_id)
												 LEFT JOIN " . TABLE_PRODUCTS_DESCRIPTION . " pd ON (p.products_id = pd.products_id)
												 LEFT JOIN " . TABLE_PRODUCT_TYPES . " pt ON (p.products_type = pt.type_id)
												 LEFT JOIN " . TABLE_SPECIALS . " s ON (s.products_id = p.products_id)
											 WHERE p.products_status = 1
												 AND p.product_is_call = 0
												 AND p.product_is_free = 0
												 AND pd.language_id = " . (int)$languages->fields['languages_id'] ."
                       GROUP BY p.products_id
											 ORDER BY p.products_id ASC";
		} else if (AMAZON_IL_ATTRIBUTES == 'true') {
			$products_query = "SELECT distinct(p.products_id), p.products_model, p.products_weight, pd.products_name, pd.products_description, p.products_image, p.products_tax_class_id, p.products_price_sorter, GREATEST(p.products_date_added, IFNULL(p.products_last_modified, 0), IFNULL(p.products_date_available, 0)) AS base_date, m.manufacturers_name, p.products_quantity, pt.type_handler, s.specials_new_products_price, s.expires_date, p.products_amazon, p.products_phrases, p.products_keywords, p.products_dim_type, p.products_weight_type, p.products_length, p.products_width, p.products_height, p.products_upc, p.products_isbn, p.products_category, p.products_condition, p.products_amazon
											 FROM " . TABLE_PRODUCTS . " p
												 LEFT JOIN " . TABLE_MANUFACTURERS . " m ON (p.manufacturers_id = m.manufacturers_id)
												 LEFT JOIN " . TABLE_PRODUCTS_DESCRIPTION . " pd ON (p.products_id = pd.products_id)
												 LEFT JOIN " . TABLE_PRODUCT_TYPES . " pt ON (p.products_type = pt.type_id)
												 LEFT JOIN " . TABLE_SPECIALS . " s ON (s.products_id = p.products_id)
											 WHERE p.products_status = 1
												 AND p.product_is_call = 0
												 AND p.product_is_free = 0
												 AND pd.language_id = " . (int)$languages->fields['languages_id'] ."
                       GROUP BY p.products_id
											 ORDER BY p.products_id ASC";
		}
		$products = $db->Execute($products_query);
		$tax_rate = array();

		$content = array();
		$content['A'] = "product-id";
		$content['B'] = "product-id-type";
		$content['C'] = "item-condition";
		$content['D'] = "price";
		$content['E'] = "sku";
		$content['F'] = "quantity";
		$content['G'] = "add-delete";
		$content['H'] = "will-ship-internationally";
		$content['I'] = "expedited-shipping";
		$content['J'] = "item-note";
		$content['K'] = "item-is-marketplace";
		$content['L'] = "item-name";
		$content['M'] = "item-description";
		$content['N'] = "category1";
		$content['O'] = "image-url";
		$content['P'] = "shipping-fee";
		$content['Q'] = "browse-path";
		$content['R'] = "storefront-feature";
		$content['S'] = "boldface";
		$content['T'] = "asin1";
		$content['U'] = "asin2";
		$content['V'] = "asin3";

		zen_amazon_fwrite($content, "wb");

		while (!$products->EOF && !$max_limit) { // run until end of file or until maximum number of products reached
			list($categories_list, $cPath) = zen_amazon_get_category((int)$products->fields['products_id']);
			if (numinix_categories_check(AMAZON_IL_POS_CATEGORIES, $products->fields['products_id'], 1) == true && numinix_categories_check(AMAZON_IL_NEG_CATEGORIES, $products->fields['products_id'], 2) == false && zen_amazon_keywords(AMAZON_IL_NEG_KEYWORDS, $products->fields['products_name'], 2) == false) { // check to see if category limits are set.  If so, only process for those categories.
        if ($anti_timeout_counter == AMAZON_IL_MAX_PRODUCTS && AMAZON_IL_MAX_PRODUCTS != 0) { // if counter is greater than or equal to maximum products
					$max_limit = true; // then max products reached
				} else {
					$max_limit = false; // otherwise, max products not reached
				}
				$price = zen_get_products_actual_price((int)$products->fields['products_id']);
				if (zen_price_check($price) && $products->fields['products_quantity'] > 0) {
					$anti_timeout_counter++;
					if (!isset($tax_rate[$products->fields['products_tax_class_id']])) {
						$tax_rate[$products->fields['products_tax_class_id']] = zen_get_tax_rate((int)$products->fields['products_tax_class_id']);
						$price = zen_add_tax($price, $tax_rate[(int)$products->fields['products_tax_class_id']]);
					}
					$price = $currencies->value($price, true, 'USD', $currencies->get_value('USD'));

					$content = array();

					if (AMAZON_IL_UPC == 'true') {
						$content["A"] = $products->fields['products_upc'];
						$content["B"] = "3";
					} else if (AMAZON_IL_ISBN == 'true') {
						$content["A"] = $products->fields['products_isbn'];
						$content["B"] = "2";
					} else {
						$content["A"] = " "; //product-id
						$content["B"] = " "; //product-id-type
					}

					if ($products->fields['products_condition'] == '') {
						$content["C"] = amazon_condition(strtolower(AMAZON_IL_CONDITION)); //item-condition
					} else {
						$content["C"] = amazon_condition(strtolower($products->fields['products_condition']));
					}
					$content['D'] = number_format($price, 2, '.', ''); //price
					$content['E'] = $products->fields['products_id']; //sku
					$content['F'] = $products->fields['products_quantity']; //quantity
					$content['G'] = "a"; //add-delete (a or d)
					$content['H'] = AMAZON_IL_INTERNATIONAL; //will-ship-internationally (y or n)
					$content['I'] = AMAZON_IL_EXPEDITED; //expedited-shipping (y or n)
					$content['J'] = " "; //item-note (up to 1000 characters)
					$content['K'] = AMAZON_IL_MARKETPLACE; //item-is-marketplace (y or n)
					// leave following blank
					$content['L'] = " "; //item-name
					$content['M'] = " "; //item-description
					$content['N'] = " "; //category1
					// following are optional
					$content['O'] = " "; //image-url
					$content['P'] = " "; //shipping-fee
					$content['Q'] = " "; //browse-path"
					$content['R'] = " "; //storefront-feature
					$content['S'] = " "; //boldface
					$content['T'] = " "; //asin1
					$content['U'] = " "; //asin2
					$content['V'] = " "; //asin3
					zen_amazon_fwrite($content, "a");

				}
			}

			$products->MoveNext();
		}
      $fc->relock($outfile);
      $fc->relock(DIR_FS_CATALOG . AMAZON_IL_DIRECTORY);
} else {
	echo 'Output file is not writeable';
}

	$timer_feed = microtime_float()-$stimer_feed;

	echo TEXT_AMAZON_IL_FEED_COMPLETE . ' ' . AMAZON_IL_TIME_TAKEN . ' ' . sprintf("%f " . TEXT_AMAZON_IL_FEED_SECONDS, number_format($timer_feed, 6) ) . ' ' . $anti_timeout_counter . TEXT_AMAZON_IL_FEED_RECORDS . NL;
}

	function amazon_condition($string) {
		if (strpos($string, 'used') !== false) {
			return '3'; // Used, Good
			break;
		} elseif (strpos($string, 'like new') !== false) {
			return '1'; // Used, Like New
			break;
		} elseif (strpos($string, 'new') !== false) {
			return '11'; // New
			break;
		}
	}

	function zen_price_check($store_price) {
		if ($store_price > 0) {
			if (AMAZON_IL_MAX_PRICE != 0) { // if max price enabled
				if ($store_price <= AMAZON_IL_MAX_PRICE && $store_price >= AMAZON_IL_MIN_PRICE) { // if price is within limits
					return true;
				}
			} else if ($store_price >= AMAZON_IL_MIN_PRICE) { // if max price is not set and price is within minimum limits (default 0)
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	function zen_amazon_keywords($words, $string, $charge) {
		if ($words != '') {
			$match = 0;
			$words = explode(",", $words);
			foreach ($words as $word) {
				if (strpos(strtolower($string), trim(strtolower($word))) !== false) {
					$match++;
					break;
				}
			}
			if ($match > 0) {
				return true;
			} else {
				return false;
			}
		} else {
			if ($charge == 1) {
				return true;
			} else if ($charge == 2) {
				return false;
			}
		}
	}

  function numinix_categories_check($categories_list, $products_id, $charge) {
    $categories_array = explode(',', $categories_list);
    if ($categories_list == '') {
      if ($charge == 1) {
        return true;
      } elseif ($charge == 2) {
        return false;
      }
    } else {
      $match = false;
      foreach($categories_array as $category_id) {
        if (zen_product_in_category($products_id, $category_id)) {
          $match = true;
          break;
        }
      }
      if ($match == true) {
        return true;
      } else {
        return false;
      }
    }
  }

	function zen_amazon_get_category($products_id) {
		global $categories_array, $db;
		static $p2c;
		if(!$p2c) {
			$q = $db->Execute("SELECT *
												FROM " . TABLE_PRODUCTS_TO_CATEGORIES);
			while (!$q->EOF) {
				if(!isset($p2c[(int)$q->fields['products_id']]))
					$p2c[(int)$q->fields['products_id']] = (int)$q->fields['categories_id'];
				$q->MoveNext();
			}
		}
		if(isset($p2c[$products_id])) {
			$retval = $categories_array[$p2c[$products_id]]['name'];
			$cPath = $categories_array[$p2c[$products_id]]['cPath'];
		} else {
			$cPath = $retval =  "";
		}
		return array($retval, $cPath);
	}

	function zen_amazon_category_tree($id_parent=0, $cPath='', $cName='', $cats=array()){
		global $db, $languages;
		$cat = $db->Execute("SELECT c.categories_id, c.parent_id, cd.categories_name
												 FROM " . TABLE_CATEGORIES . " c
													 LEFT JOIN " . TABLE_CATEGORIES_DESCRIPTION . " cd on c.categories_id = cd.categories_id
												 WHERE c.parent_id = '" . (int)$id_parent . "'
												 AND cd.language_id='" . (int)$languages->fields['languages_id'] . "'
												 AND c.categories_status= '1'",
												 '', false, 150);
		while (!$cat->EOF) {
			$cats[(int)$cat->fields['categories_id']]['name'] = (zen_not_null($cName) ? $cName . ', ' : '') . trim($cat->fields['categories_name']); // previously used zen_amazon_sanita instead of trim
			$cats[(int)$cat->fields['categories_id']]['cPath'] = (zen_not_null($cPath) ? $cPath . '_' : '') . (int)$cat->fields['categories_id'];
			if (zen_has_category_subcategories((int)$cat->fields['categories_id'])) {
				$cats = zen_amazon_category_tree((int)$cat->fields['categories_id'], $cats[(int)$cat->fields['categories_id']]['cPath'], $cats[(int)$cat->fields['categories_id']]['name'], $cats);
			}
			$cat->MoveNext();
		}
		return $cats;
	}

	function zen_amazon_fwrite($output, $mode) {
		$output = implode(",", $output);
		$output .= "\n";
		$fp = fopen(DIR_FS_CATALOG . AMAZON_IL_DIRECTORY . AMAZON_IL_OUTPUT_FILENAME, $mode);
		$retval = fwrite($fp, $output, AMAZON_IL_OUTPUT_BUFFER_MAXSIZE);
		return $retval;
	}

	function microtime_float() {
	   list($usec, $sec) = explode(" ", microtime());
	   return ((float)$usec + (float)$sec);
	}
?>
